﻿
using System;
using System.Diagnostics;

namespace nhCore.Modbus
{
    /// <summary>
    /// 电量解码器，计算要素
    /// </summary>
    public class PowerDecoder : WeatherDecoder
    {
        /// <summary>
        /// 空电量电压
        /// </summary>
        private readonly double VoltageEmpth = 3.7;
        /// <summary>
        /// 满电量电压
        /// </summary>
        private readonly double VoltageFull = 4.1;
             
        public PowerDecoder(ElementConfig config)
        {
            Name = "电量解码器，计算要素";
            Config = config;
        }

        public override double? DeCode(FrameValid mb)
        {
            double? power = null;

            if (mb == null)
            {
                Debug.WriteLine($"{Name}.DeCode()mb为空");
            }
            else
            {
                double? voltage = base.DeCode(mb) / 100;//按小数点零解码后还原为电压
                if (voltage != null)
                {
                    power = (voltage - VoltageEmpth) / (VoltageFull - VoltageEmpth);
                    power *= 100;
                    power = Math.Ceiling((double)power);//取整
                    power = Math.Min(100, (double)power);//取最小
                }
            }
            return power;
        }
    }
}
